<?php

namespace App\Exports;

use App\Enums\AssetStatus;
use App\Models\Asset;
use App\Models\Download;
use Illuminate\Support\Arr;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class UserAssetExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        return Asset::query()
            ->select(['user_id', 'contract_address', 'token_id', 'cert_sn', 'created_at', 'asset_status'])
            ->where('user_id', Arr::get($this->request, 'user_id'))
            ->whereIn('asset_status', [AssetStatus::HOLD, AssetStatus::ON_SALE])
            ->with(['product']);
    }

    public function map($asset): array // 指定excel中每一列的数据字段
    {
        /* @var Asset $asset */
        return [
            $asset->contract_address,
            $asset->product->name,
            ' ' . $asset->token_id,
            $asset->cert_sn,
            $asset->user->mobile,
            $asset->created_at->toDateTimeString(),
            $asset->asset_status->description,
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return ['资产标识', '商品名称', '存证ID', '证书编号', '持有人', '存证时间', '持有状态'];
    }
}
